import sys
import json
import socket
import threading
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from pyqt5_plugins.examplebutton import QtWidgets

from ui.net_assist_widget import Ui_NetAssistWidget


def get_local_ips():
    """获取本机所有的 IPv4 地址"""
    local_ips = []
    try:
        hostname = socket.gethostname()  # 获取主机名
        local_ips = socket.gethostbyname_ex(hostname)[2]  # 获取所有 IP
    except Exception as e:
        print(f"获取本地 IP 失败: {e}")

    return local_ips if local_ips else ["127.0.0.1"]  # 默认返回 127.0.0.1


def calculate_and_convert(binary_prefix, volt):
    """计算并转换电压值"""
    try:
        volt = float(volt) if volt else 0  # ✅ 确保 volt 是数值
    except ValueError:
        volt = 0

    result = (volt / 60) * 4095
    result = min(max(result, 0), 4095)  # ✅ 限制范围

    hex_result = int(result)
    hex_str = f"{hex_result:03x}"
    binary_str = binary_prefix + bin(int(hex_str, 16))[2:].zfill(12)
    final_hex = f"{int(binary_str, 2):04x}".upper()

    byte1, byte2 = final_hex[:2], final_hex[2:]
    return f" {byte2} {byte1}"


def calculate_and_convert_th(binary_prefix,volt):
    if volt=="":
        volt=0
    result = (float(volt) / 3.3) * 4095
    if result>=4095:
        result=4095
    hex_result = int(result)
    hex_str = f"{hex_result:03x}"
    binary_str = binary_prefix + bin(int(hex_str, 16))[2:].zfill(12)
    final_hex = f"{int(binary_str, 2):04x}".upper()
    byte1 = final_hex[:2]
    byte2 = final_hex[2:]
    return " "+byte2+" "+byte1

def process_data(data):
    # 提取后3位并转换为十进制数
    eff_str = data[1][-3:]
    eff_num = int(eff_str, 16)
    result = (eff_num / 4096) * 60
    new_str = f"{data[0]}: {result:.2f} V"
    return new_str
class NetAssistWidget1(QWidget):
    data_received = pyqtSignal(str)  # 信号，用于传输接收到的数据
    connection_status = pyqtSignal(bool)  # 新增信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.main_window: QMainWindow = parent
        self.ui = Ui_NetAssistWidget()
        self.ui.setupUi(self)

        self.tcp_client = None  # TCP 客户端
        self.data_num_sended = 0  # 记录发送的数据量
        self.data_num_revced = 0  # 记录发送的数据量

        self.timer = QTimer()  # 创建定时器
        self.timer.timeout.connect(self.data_update)  # 连接超时信号到 data_update 方法

        self.init_ui()


    def init_ui(self):
        """初始化 UI 并填充本地 IP"""
        self.ui.edit_target_ip.setText("192.168.1.10")
        self.ui.edit_target_port.setText("5010")

        # ✅ 获取并填充本地 IP
        local_ips = get_local_ips()
        print("本地 IP 列表:", local_ips)  # 调试用
        self.ui.cb_local_ip.addItems(local_ips)  # 填充下拉框
        self.ui.cb_local_ip.setCurrentIndex(0)  # 选中第一个 IP

        # 初始化 checkBox 状态
        self.ui.checkBox.setChecked(False)  # 初始状态为未勾选
        self.ui.checkBox.stateChanged.connect(self.toggle_timer)  # 连接状态改变信号
        # 连接信号槽
        self.ui.btn_connect.clicked.connect(self.on_connect_clicked)

        # 设置 lineEditTimer 的占位符文本
        self.ui.lineEditTimer.setPlaceholderText("间隔时间（毫秒）")
        self.connection_status.connect(self.update_connect_status)  # 连接信号到槽

        self.ui.pushButton.clicked.connect(self.data_update)
        self.ui.pushButtonA1.clicked.connect(self.A_data_send)
        self.ui.pushButtonA2.clicked.connect(self.A_data_rst)
        self.ui.pushButtonB1.clicked.connect(self.B_data_send)
        self.ui.pushButtonB2.clicked.connect(self.B_data_rst)
        self.ui.pushButtonTh.clicked.connect(self.th_data_send)

        self.data_received.connect(self.update_text)
        self.ui.pushButton_byte.clicked.connect(self.byte_rst)
        self.ui.pushButton_recv_rst.clicked.connect(self.rst_data_recv_text)
        # 假设有两个按钮分别用于保存和加载
        self.ui.saveButton.clicked.connect(self.save_line_edits)
        self.ui.loadButton.clicked.connect(self.load_line_edits)
        self.ui.pushButton_rest.clicked.connect(self.parameter_rst)
        self.ui.comboBox.currentIndexChanged.connect(self.on_combobox_changed)
        self.ui.tabWidget.currentChanged.connect(self.update_combo_box)

        self.ui.pushButtonA1_2.clicked.connect(self.A_data_send)
        self.ui.pushButtonA2_2.clicked.connect(self.A_data_rst)
        self.ui.pushButtonB1_2.clicked.connect(self.B_data_send)
        self.ui.pushButtonB2_2.clicked.connect(self.B_data_rst)
        self.ui.pushButtonTh_2.clicked.connect(self.th_data_send)
        self.ui.pushButton_rest_2.clicked.connect(self.parameter_rst)
    def on_combobox_changed(self, index):
        """当 ComboBox 选择变化时，切换 TabWidget"""
        self.ui.tabWidget.setCurrentIndex(index)

    def update_combo_box(self):
        current_index = self.ui.tabWidget.currentIndex()
        self.ui.comboBox.setCurrentIndex(current_index)

    def toggle_timer(self, state):
        """根据 checkBox 的状态启动或停止定时器"""
        if state == Qt.Checked:
            if self.timer.isActive():
                self.timer.stop() # 如果勾选
            try:
                interval = int(self.ui.lineEditTimer.text())  # 读取 lineEdit 的值作为间隔
                if interval > 0:
                    self.timer.start(interval)  # 启动定时器
                    print(f"定时器启动，间隔: {interval} 毫秒")
                else:
                    QMessageBox.warning(self, '警告', '请输入大于0的间隔时间！')
            except ValueError:
                QMessageBox.critical(self, '错误', '请输入有效的整数作为间隔时间！')
        else:  # 如果未勾选
            self.timer.stop()
            self.timer.deleteLater()  # 显式释放资源
            self.timer = QTimer()  # 重新创建新定时器

    def update_connect_status(self):
        """更新连接状态"""
        if self.tcp_client is not None:
            self.ui.btn_connect.setText("断开连接（已连接）")
            icon = QIcon()
            icon.addPixmap(QPixmap(":/icon/connect"))
            self.ui.btn_connect.setIcon(icon)
        else:
            self.ui.btn_connect.setText("连接网络")
            icon = QIcon()
            icon.addPixmap(QPixmap(":/icon/disc"))
            self.ui.btn_connect.setIcon(icon)

    def run_tcp_client(self, target_ip, target_port):
        """运行 TCP 客户端"""
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.tcp_client.connect((target_ip, int(target_port)))
            print(f"连接成功: {target_ip}:{target_port}")

            local_port = self.tcp_client.getsockname()[1]
            QMetaObject.invokeMethod(self.ui.edit_local_port, "setText", Qt.QueuedConnection,
                                     Q_ARG(str, str(local_port)))

            self.connection_status.emit(True)  # 使用信号通知状态变化

            while True:
                try:
                    bytes_data = self.tcp_client.recv(2048)
                    if not bytes_data:
                        print("服务器断开连接")
                        break

                    str_data = bytes_data.decode("utf-8", errors="ignore")
                    print("收到数据:", str_data)

                    QMetaObject.invokeMethod(self, "emit_data_received", Qt.QueuedConnection, Q_ARG(str, str_data))

                except (ConnectionResetError, BrokenPipeError):
                    print("连接已断开")
                    break
        except Exception as e:
            print(f"连接失败: {e}")
        finally:
            if self.tcp_client:
                self.tcp_client.close()
            self.tcp_client = None
            self.connection_status.emit(False)  # 通知断开连接
    @pyqtSlot(str)
    def emit_data_received(self, data):
        """在主线程处理接收的数据"""
        self.data_received.emit(data)

    def handle_client_connect(self):
        """处理客户端连接"""
        if self.tcp_client:
            try:
                self.tcp_client.shutdown(socket.SHUT_RDWR)  # 先关闭连接
                self.tcp_client.close()
            except OSError as e:
                print(f"关闭连接时出错: {e}")
            finally:
                self.tcp_client = None
                QThread.msleep(100)  # 等待资源释放
                return

        target_ip = self.ui.edit_target_ip.text()
        target_port = self.ui.edit_target_port.text()
        print(f"尝试连接服务器: {target_ip}:{target_port}")

        if target_ip == "" or target_port == "":
            print("请先输入 IP 和端口号")
            return

        thread = threading.Thread(target=self.run_tcp_client, args=(target_ip, target_port), daemon=True)
        thread.start()


    def on_connect_clicked(self):
        self.handle_client_connect()

    #发送数据
    def data_update(self):
        if self.tcp_client:  # 检查是否已连接到 TCP
            # 根据 comboBox 的当前索引选择不同的起始值
            if self.ui.comboBox.currentIndex() == 0:
                input_s = "30 30 00 00 00 00 00 00 00 00 0d 0a"
            elif self.ui.comboBox.currentIndex() == 1:
                input_s = "31 30 00 00 00 00 00 00 00 00 0d 0a"
            else:
                QMessageBox.warning(self, '警告', '无效的选项，请选择正确的模式！')
                return
            # 示例数据
            if input_s.strip():  # 检查非空字符串
                # hex发送
                send_list = []
                while input_s:  # 将输入分割成字节
                    try:
                        num = int(input_s[0:2], 16)  # 转换前两个字符为十六进制整数
                        send_list.append(num)
                        input_s = input_s[2:].strip()  # 删除已处理的两个字符
                    except ValueError:
                        QMessageBox.critical(self, '错误', '请输入有效的十六进制数据，以空格分开！')
                        return None

                input_bytes = bytes(send_list)  # 转换为字节

                try:
                    num = self.tcp_client.send(input_bytes)  # 通过 TCP 发送数据
                    print('发送数据:', ' '.join(f"{b:02X}" for b in input_bytes))  # 打印发送的数据
                    self.data_num_sended += num  # 更新发送的数据字节数
                    self.ui.lineEdit_TX.setText(str(self.data_num_sended) + ' Byte')
                except Exception as e:
                    QMessageBox.critical(self, '发送错误', f'发送数据失败: {e}')
        else:
            QMessageBox.warning(self, '警告', '请先建立 TCP 连接！')

    def A_data_send(self):
        if self.tcp_client:  # 检查是否已连接
            # 根据 comboBox 的当前索引选择不同的起始值
            if self.ui.comboBox.currentIndex() == 0:
                msg_ad5504 = "30 34"
                msg_ad5504 += calculate_and_convert("0001", self.ui.lineEditA1.text())
                msg_ad5504 += calculate_and_convert("0010", self.ui.lineEditA2.text())
                msg_ad5504 += calculate_and_convert("0011", self.ui.lineEditA3.text())
                msg_ad5504 += calculate_and_convert("0100", self.ui.lineEditA4.text())
            elif self.ui.comboBox.currentIndex() == 1:
                msg_ad5504 = "31 34"
                msg_ad5504 += calculate_and_convert("0001", self.ui.lineEditA1_2.text())
                msg_ad5504 += calculate_and_convert("0010", self.ui.lineEditA2_2.text())
                msg_ad5504 += calculate_and_convert("0011", self.ui.lineEditA3_2.text())
                msg_ad5504 += calculate_and_convert("0100", self.ui.lineEditA4_2.text())
            else:
                QMessageBox.warning(self, '警告', '无效的选项，请选择正确的模式！')
                return
            input_s = msg_ad5504 + " 0d 0a"  # 组合消息

            if input_s.strip() != "":  # 检查非空字符串
                # hex发送
                input_s = input_s.strip()
                send_list = []
                while input_s != '':
                    try:
                        num = int(input_s[0:2], 16)  # 将前两个字符转换为十六进制
                    except ValueError:
                        QMessageBox.critical(self, 'wrong data', '请输入十六进制数据，以空格分开!')
                        return None
                    input_s = input_s[2:].strip()  # 删除已处理的两个字符
                    send_list.append(num)

                input_s = bytes(send_list)  # 转换为字节

                # 发送数据
                try:
                    self.tcp_client.send(input_s)  # 通过 TCP 发送数据
                    print('发送数据:', ' '.join(f"{b:02X}" for b in input_s))  # 打印发送的数据
                    self.data_num_sended += len(input_s)  # 更新发送的数据字节数
                    self.ui.lineEdit_TX.setText(str(self.data_num_sended) + ' Byte')

                except Exception as e:
                    QMessageBox.critical(self, '发送错误', f'发送数据失败: {e}')
            else:
                QMessageBox.warning(self, '警告', '发送内容不能为空！')
        else:
            QMessageBox.warning(self, '警告', '请先建立 TCP 连接！')

    def A_data_rst(self):
        if self.tcp_client:  # 检查是否已连接到 TCP
            # 根据 comboBox 的当前索引选择不同的起始值
            if self.ui.comboBox.currentIndex() == 0:
                input_s = "30 35 00 00 00 00 00 00 00 00 0d 0a"
            elif self.ui.comboBox.currentIndex() == 1:
                input_s = "31 35 00 00 00 00 00 00 00 00 0d 0a"
            else:
                QMessageBox.warning(self, '警告', '无效的选项，请选择正确的模式！')
                return
            # 示例数据
            if input_s.strip():  # 检查非空字符串
                # hex发送
                send_list = []
                while input_s:  # 将输入分割成字节
                    try:
                        num = int(input_s[0:2], 16)  # 转换前两个字符为十六进制整数
                        send_list.append(num)
                        input_s = input_s[2:].strip()  # 删除已处理的两个字符
                    except ValueError:
                        QMessageBox.critical(self, '错误', '请输入有效的十六进制数据，以空格分开！')
                        return None

                input_bytes = bytes(send_list)  # 转换为字节

                try:
                    num = self.tcp_client.send(input_bytes)  # 通过 TCP 发送数据
                    print('发送数据:', ' '.join(f"{b:02X}" for b in input_bytes))  # 打印发送的数据
                    self.data_num_sended += num  # 更新发送的数据字节数
                    self.ui.lineEdit_TX.setText(str(self.data_num_sended) + ' Byte')
                except Exception as e:
                    QMessageBox.critical(self, '发送错误', f'发送数据失败: {e}')
        else:
            QMessageBox.warning(self, '警告', '请先建立 TCP 连接！')

    def B_data_send(self):
        if self.tcp_client:  # 检查是否已连接
            # 根据 comboBox 的当前索引选择不同的起始值
            if self.ui.comboBox.currentIndex() == 0:
                msg_ad5504 = "30 36"
                msg_ad5504 += calculate_and_convert("0001", self.ui.lineEditB1.text())
                msg_ad5504 += calculate_and_convert("0010", self.ui.lineEditB2.text())
                msg_ad5504 += calculate_and_convert("0011", self.ui.lineEditB3.text())
                msg_ad5504 += calculate_and_convert("0100", self.ui.lineEditB4.text())
            elif self.ui.comboBox.currentIndex() == 1:
                msg_ad5504 = "31 36"
                msg_ad5504 += calculate_and_convert("0001", self.ui.lineEditB1_2.text())
                msg_ad5504 += calculate_and_convert("0010", self.ui.lineEditB2_2.text())
                msg_ad5504 += calculate_and_convert("0011", self.ui.lineEditB3_2.text())
                msg_ad5504 += calculate_and_convert("0100", self.ui.lineEditB4_2.text())
            else:
                QMessageBox.warning(self, '警告', '无效的选项，请选择正确的模式！')
                return
            input_s = msg_ad5504 + " 0d 0a"  # 组合消息

            if input_s.strip() != "":  # 检查非空字符串
                # hex发送
                input_s = input_s.strip()
                send_list = []
                while input_s != '':
                    try:
                        num = int(input_s[0:2], 16)  # 将前两个字符转换为十六进制
                    except ValueError:
                        QMessageBox.critical(self, 'wrong data', '请输入十六进制数据，以空格分开!')
                        return None
                    input_s = input_s[2:].strip()  # 删除已处理的两个字符
                    send_list.append(num)

                input_s = bytes(send_list)  # 转换为字节

                # 发送数据
                try:
                    self.tcp_client.send(input_s)  # 通过 TCP 发送数据
                    print('发送数据:', ' '.join(f"{b:02X}" for b in input_s))  # 打印发送的数据
                    self.data_num_sended += len(input_s)  # 更新发送的数据字节数
                    self.ui.lineEdit_TX.setText(str(self.data_num_sended) + ' Byte')

                except Exception as e:
                    QMessageBox.critical(self, '发送错误', f'发送数据失败: {e}')
            else:
                QMessageBox.warning(self, '警告', '发送内容不能为空！')
        else:
            QMessageBox.warning(self, '警告', '请先建立 TCP 连接！')

    def B_data_rst(self):
        if self.tcp_client:  # 检查是否已连接到 TCP
            # 根据 comboBox 的当前索引选择不同的起始值
            if self.ui.comboBox.currentIndex() == 0:
                input_s = "30 37 00 00 00 00 00 00 00 00 0d 0a"
            elif self.ui.comboBox.currentIndex() == 1:
                input_s = "31 37 00 00 00 00 00 00 00 00 0d 0a"
            else:
                QMessageBox.warning(self, '警告', '无效的选项，请选择正确的模式！')
                return
            # 示例数据
            if input_s.strip():  # 检查非空字符串
                # hex发送
                send_list = []
                while input_s:  # 将输入分割成字节
                    try:
                        num = int(input_s[0:2], 16)  # 转换前两个字符为十六进制整数
                        send_list.append(num)
                        input_s = input_s[2:].strip()  # 删除已处理的两个字符
                    except ValueError:
                        QMessageBox.critical(self, '错误', '请输入有效的十六进制数据，以空格分开！')
                        return None

                input_bytes = bytes(send_list)  # 转换为字节

                try:
                    num = self.tcp_client.send(input_bytes)  # 通过 TCP 发送数据
                    print('发送数据:', ' '.join(f"{b:02X}" for b in input_bytes))  # 打印发送的数据
                    self.data_num_sended += num  # 更新发送的数据字节数
                    self.ui.lineEdit_TX.setText(str(self.data_num_sended) + ' Byte')
                except Exception as e:
                    QMessageBox.critical(self, '发送错误', f'发送数据失败: {e}')
        else:
            QMessageBox.warning(self, '警告', '请先建立 TCP 连接！')

    def th_data_send(self):
        if self.tcp_client:  # 检查是否已连接到 TCP
            # 根据 comboBox 的当前索引选择不同的起始值
            if self.ui.comboBox.currentIndex() == 0:
                msg_ad5504 = "30 38"
            elif self.ui.comboBox.currentIndex() == 1:
                msg_ad5504 = "31 38"
            else:
                QMessageBox.warning(self, '警告', '无效的选项，请选择正确的模式！')
                return
            msg_ad5504 += calculate_and_convert_th("0001", self.ui.lineEditTh.text())
            msg_ad5504 += calculate_and_convert_th("0010", 0)
            input_s = msg_ad5504 + " 00 00 00 00 0d 0a"

            if input_s.strip() != "":
                # 非空字符串
                input_s = input_s.strip()
                send_list = []
                while input_s != '':
                    try:
                        num = int(input_s[0:2], 16)
                    except ValueError:
                        QMessageBox.critical(self, '错误', '请输入有效的十六进制数据，以空格分开!')
                        return None
                    input_s = input_s[2:].strip()
                    send_list.append(num)

                input_bytes = bytes(send_list)  # 转换为字节
                print('发送数据:', ' '.join(f"{b:02X}" for b in input_bytes))  # 打印发送的数据

                try:
                    num = self.tcp_client.send(input_bytes)  # 通过 TCP 发送数据
                    self.data_num_sended += num  # 更新发送的数据字节数
                    self.ui.lineEdit_TX.setText(str(self.data_num_sended) + ' Byte')
                except Exception as e:
                    QMessageBox.critical(self, '发送错误', f'发送数据失败: {e}')
        else:
            QMessageBox.warning(self, '警告', '请先建立 TCP 连接！')

    #更新接收信息
    def update_text(self, data):
        """在 UI 上显示接收到的数据"""
        try:
            self.data_num_revced += len(data)
            self.ui.lineEdit_RX.setText(f"{self.data_num_revced} Byte")

            msg = "".join(data).replace("@", ":")
            parts = msg.split("=")

            if not parts or len(parts) < 25:  # 确保数据完整
                print("收到的数据格式不正确，忽略处理")
                return

            try:
                last_part = int(parts[-1])  # 解析最后一个部分
            except ValueError:
                print("数据格式错误，无法解析最后一个字段")
                return

            line_edit_names_first = [
                f"lineEdit_{i}" for i in range(1, 17)
            ]

            line_edit_names_second = [
                f"lineEdit_{i}" for i in range(34, 50)
            ]

            def update_line_edits(line_edit_names, parts, start_index=0):
                for i in range(min(len(line_edit_names), len(parts))):
                    line_edit = getattr(self.ui, line_edit_names[i], None)
                    if line_edit:
                        line_edit.setText(parts[start_index + i])

            if last_part == 30:
                update_line_edits(line_edit_names_first, parts)

                # Update line edits from parts[17] to parts[24]
                for i in range(17, min(25, len(parts))):
                    line_edit = getattr(self.ui, f"lineEdit_{i}", None)
                    if line_edit:
                        line_edit.setText(process_data(parts[i].split(":")))

                if len(parts) > 16:
                    self.ui.lineEdit_33.setText(parts[16])

            elif last_part == 31:
                update_line_edits(line_edit_names_second, parts)

                # Update line edits from parts[17] to parts[24] for second case
                for i in range(17, min(25, len(parts))):
                    line_edit_name = f"lineEdit_{i + 33}"  # lineEdit_50 to lineEdit_57
                    line_edit = getattr(self.ui, line_edit_name, None)
                    if line_edit and len(parts) > i:
                        line_edit.setText(process_data(parts[i].split(":")))

                if len(parts) > 16:
                    self.ui.lineEdit_66.setText(parts[16])

        except AttributeError as e:
            print(f"UI 属性未找到: {e}")
        except Exception as e:
            print(f"update_text 处理数据时发生错误: {e}")

    #重置接收字节
    def byte_rst(self):
        self.data_num_sended = 0
        self.data_num_revced = 0
        self.ui.lineEdit_TX.setText(str(''))
        self.ui.lineEdit_RX.setText(str(''))

    #重置接收文本框
    def rst_data_recv_text(self):
        """重置接收文本框的内容"""
        for i in range(1, 67):
            try:
                line_edit = getattr(self.ui, f'lineEdit_{i}', None)
                if line_edit is not None:
                    line_edit.setText('')
            except AttributeError:
                print(f"警告：lineEdit_{i} 不存在")

    def save_line_edits(self):
        """保存所有 lineEdit 文本值到文件"""
        filename, _ = QtWidgets.QFileDialog.getSaveFileName(self, "保存文件", "", "JSON 文件 (*.json)")
        if filename:  # 确保用户选择了文件名
            data = {
                'lineEdit1_1': self.ui.lineEditA1.text(), 'lineEdit1_2': self.ui.lineEditA2.text(),
                'lineEdit1_3': self.ui.lineEditA3.text(), 'lineEdit1_4': self.ui.lineEditA4.text(),
                'lineEdit1_5': self.ui.lineEditB1.text(), 'lineEdit1_6': self.ui.lineEditB2.text(),
                'lineEdit1_7': self.ui.lineEditB3.text(), 'lineEdit1_8': self.ui.lineEditB4.text(),
                'lineEdit1_9': self.ui.lineEditC1.text(), 'lineEdit1_10': self.ui.lineEditC2.text(),
                'lineEdit1_11': self.ui.lineEditC3.text(), 'lineEdit1_12': self.ui.lineEditC4.text(),
                'lineEdit1_13': self.ui.lineEditD1.text(), 'lineEdit1_14': self.ui.lineEditD2.text(),
                'lineEdit1_15': self.ui.lineEditD3.text(), 'lineEdit1_16': self.ui.lineEditD4.text(),
                'lineEdit1_17': self.ui.lineEditTh.text(),
                'lineEdit2_1': self.ui.lineEditA1_2.text(), 'lineEdit2_2': self.ui.lineEditA2_2.text(),
                'lineEdit2_3': self.ui.lineEditA3_2.text(), 'lineEdit2_4': self.ui.lineEditA4_2.text(),
                'lineEdit2_5': self.ui.lineEditB1_2.text(), 'lineEdit2_6': self.ui.lineEditB2_2.text(),
                'lineEdit2_7': self.ui.lineEditB3_2.text(), 'lineEdit2_8': self.ui.lineEditB4_2.text(),
                'lineEdit2_9': self.ui.lineEditC1_2.text(), 'lineEdit2_10': self.ui.lineEditC2_2.text(),
                'lineEdit2_11': self.ui.lineEditC3_2.text(), 'lineEdit2_12': self.ui.lineEditC4_2.text(),
                'lineEdit2_13': self.ui.lineEditD1_2.text(), 'lineEdit2_14': self.ui.lineEditD2_2.text(),
                'lineEdit2_15': self.ui.lineEditD3_2.text(), 'lineEdit2_16': self.ui.lineEditD4_2.text(),
                'lineEdit2_17': self.ui.lineEditTh_2.text(),
            }

            # 将数据写入 JSON 文件
            with open(filename, 'w') as file:
                json.dump(data, file)
            print(f"文件已保存到: {filename}")  # 输出保存的文件地址

    def load_line_edits(self):
        """从文件读取文本值并设置到所有 lineEdit"""
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, "打开文件", "", "JSON 文件 (*.json)")
        if filename:  # 确保用户选择了文件名
            try:
                with open(filename, 'r') as file:
                    data = json.load(file)  # 读取 JSON 文件

                # 设置每个 lineEdit 的文本值
                self.ui.lineEditA1.setText(data.get('lineEdit1_1', ''))
                self.ui.lineEditA2.setText(data.get('lineEdit1_2', ''))
                self.ui.lineEditA3.setText(data.get('lineEdit1_3', ''))
                self.ui.lineEditA4.setText(data.get('lineEdit1_4', ''))
                self.ui.lineEditB1.setText(data.get('lineEdit1_5', ''))
                self.ui.lineEditB2.setText(data.get('lineEdit1_6', ''))
                self.ui.lineEditB3.setText(data.get('lineEdit1_7', ''))
                self.ui.lineEditB4.setText(data.get('lineEdit1_8', ''))
                self.ui.lineEditC1.setText(data.get('lineEdit1_9', ''))
                self.ui.lineEditC2.setText(data.get('lineEdit1_10', ''))
                self.ui.lineEditC3.setText(data.get('lineEdit1_11', ''))
                self.ui.lineEditC4.setText(data.get('lineEdit1_12', ''))
                self.ui.lineEditD1.setText(data.get('lineEdit1_13', ''))
                self.ui.lineEditD2.setText(data.get('lineEdit1_14', ''))
                self.ui.lineEditD3.setText(data.get('lineEdit1_15', ''))
                self.ui.lineEditD4.setText(data.get('lineEdit1_16', ''))
                self.ui.lineEditTh.setText(data.get('lineEdit1_17', ''))

                self.ui.lineEditA1_2.setText(data.get('lineEdit2_1', ''))
                self.ui.lineEditA2_2.setText(data.get('lineEdit2_2', ''))
                self.ui.lineEditA3_2.setText(data.get('lineEdit2_3', ''))
                self.ui.lineEditA4_2.setText(data.get('lineEdit2_4', ''))
                self.ui.lineEditB1_2.setText(data.get('lineEdit2_5', ''))
                self.ui.lineEditB2_2.setText(data.get('lineEdit2_6', ''))
                self.ui.lineEditB3_2.setText(data.get('lineEdit2_7', ''))
                self.ui.lineEditB4_2.setText(data.get('lineEdit2_8', ''))
                self.ui.lineEditC1_2.setText(data.get('lineEdit2_9', ''))
                self.ui.lineEditC2_2.setText(data.get('lineEdit2_10', ''))
                self.ui.lineEditC3_2.setText(data.get('lineEdit2_11', ''))
                self.ui.lineEditC4_2.setText(data.get('lineEdit2_12', ''))
                self.ui.lineEditD1_2.setText(data.get('lineEdit2_13', ''))
                self.ui.lineEditD2_2.setText(data.get('lineEdit2_14', ''))
                self.ui.lineEditD3_2.setText(data.get('lineEdit2_15', ''))
                self.ui.lineEditD4_2.setText(data.get('lineEdit2_16', ''))
                self.ui.lineEditTh_2.setText(data.get('lineEdit2_17', ''))

                print(f"文件已加载: {filename}")  # 输出加载的文件地址
            except FileNotFoundError:
                print(f"{filename} 文件未找到！")
            except json.JSONDecodeError:
                print("文件内容无法解析为 JSON 格式！")

    #重置参数
    def parameter_rst(self):
        # 创建一个包含所有要清空的 lineEdit 控件的列表
        line_edits = [
            self.ui.lineEditA1, self.ui.lineEditA2, self.ui.lineEditA3, self.ui.lineEditA4,
            self.ui.lineEditB1, self.ui.lineEditB2, self.ui.lineEditB3, self.ui.lineEditB4,
            self.ui.lineEditC1, self.ui.lineEditC2, self.ui.lineEditC3, self.ui.lineEditC4,
            self.ui.lineEditD1, self.ui.lineEditD2, self.ui.lineEditD3, self.ui.lineEditD4,
            self.ui.lineEditTh,
            self.ui.lineEditA1_2, self.ui.lineEditA2_2, self.ui.lineEditA3_2, self.ui.lineEditA4_2,
            self.ui.lineEditB1_2, self.ui.lineEditB2_2, self.ui.lineEditB3_2, self.ui.lineEditB4_2,
            self.ui.lineEditC1_2, self.ui.lineEditC2_2, self.ui.lineEditC3_2, self.ui.lineEditC4_2,
            self.ui.lineEditD1_2, self.ui.lineEditD2_2, self.ui.lineEditD3_2, self.ui.lineEditD4_2,
            self.ui.lineEditTh_2
        ]

        # 使用循环清空所有 lineEdit 控件
        for line_edit in line_edits:
            line_edit.setText('')


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = QMainWindow()
    net_assist = NetAssistWidget1(parent=window)
    window.setCentralWidget(net_assist)
    window.show()
    sys.exit(app.exec_())
